package com.ziyia.navigationview;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class ElementAdapter extends RecyclerView.Adapter<ElementAdapter.ViewHolder> {

    private Context context;
    private List<Element> lists;

    public ElementAdapter(Context context, List<Element> list) {
        this.context = context;
        this.lists = list;
    }

    @NonNull
    @NotNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.element, parent, false);
        ViewHolder viewHolder = new ViewHolder(inflate);
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int po = viewHolder.getAdapterPosition();
                Element element = lists.get(po);
                Toast.makeText(context, element.toString(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(context, ElementActivity.class);
                intent.putExtra(ElementActivity.ELEMENT_NAME, element.getName());
                intent.putExtra(ElementActivity.ELEMENT_IMAGE_ID, element.getImageId());
                intent.putExtra("obj", element.toString());
                context.startActivity(intent);
            }
        });
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull ElementAdapter.ViewHolder holder, int position) {
        Element element = lists.get(position);
        holder.name.setText(element.getName());
//        holder.imageId.setImageBitmap(BitmapFactory.decodeResource(holder.itemView.getResources(), element.getImageId()));
//        Glide.with(context).load(element.getImageId()).into(holder.imageId);

        if (position%2 != 0) {
            Glide.with(context).load("http://test.ziyia.cn/images/1.jpg").into(holder.imageId);
        } else {
            Glide.with(context).load("http://test.ziyia.cn/images/2.jpg").into(holder.imageId);

        }

    }

    @Override
    public int getItemCount() {
        return lists.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView name;
        private ImageView imageId;
        public ViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.elementName);
            imageId = itemView.findViewById(R.id.elementImage);
        }
    }
}
